import React, { Component } from "react";
import { InputNumber, Checkbox, Divider, Form, Input, Radio, Row, Col, message, TreeSelect } from "antd";
import { connect } from "dva";
import "./RightTwo.less";
import UploadDu from "./UploadDu";
import { noImg } from "../../utils/request";
import { PushDraftList } from "../../services/services";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const { SHOW_PARENT } = TreeSelect;

@connect(({ add }) => ({
  add: add
}))
class RightTwo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      radioValue: 1,
      radioValue2: 0,
      showCover: 1,
      editData: "",
      editDatas: [],
      scanNum: 0,
      forwardNum: 0,
      thumbsNum: 0,
      forwardNumPro: 0,
      thumbsNumPro: 0,
      scanNumPro: 0,
      config_json: {},
      mplist: [],
      siteTreeData: []
    };
    this.getFieldsValue = this.getFieldsValue.bind(this);
  }
  componentDidMount() {
    this.props.onRef(this);
    let userinfo = localStorage.getItem("userInfo");
    //编辑名称默认为登陆管理员
    if (userinfo) {
      if (typeof userinfo === "string") {
        userinfo = JSON.parse(userinfo);
      }

      this.props.form.setFieldsValue({
        editor: userinfo.real_name
      });
    }

    window.PubSub.subscribe("pushDataToContent2", this.pushDataToContent);
    this.getSiteList();
  }
  pushDataToContent = item => {
    this.props.form.setFieldsValue(item);
  };
  // 获取站点列表
  getSiteList = () => {
    const params = {
      site_id: 1 //this.props.match.params.List
    };
    PushDraftList(params)
      .then(res => {
        if (res.code === 200) {
          let siteTreeData = [
            {
              title: "全部",
              value: 0,
              key: 0,
              children: []
            }
          ];
          res.data.length &&
            res.data.forEach(item => {
              let obj = {};
              obj.value = item.site_id;
              obj.title = item.site_name;
              obj.key = item.site_id;
              siteTreeData[0]["children"].push(obj);
            });
          this.setState({
            siteTreeData
          });
        } else if (res.code === 500) {
          message.error(res.msg);
        } else {
          message.error("连接失败");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  onChangeRadio = e => {
    this.setState({
      radioValue: e.target.value,
      editDatas: []
    });
    this.props.form.setFieldsValue({
      is_original: e.target.value
    });
  };
  /**
   * 获取表单的值
   */
  getFieldsValueTab = () => {
    let data = this.props.form.getFieldsValue();
    let about = [];
    data["about"] = about.join();
    data["img_arr"] = this.state.imgList;
    data["type"] = 2;
    return data;
  };
  getFieldsValue = () => {
    let data = this.props.form.getFieldsValue();
    this.props.form.validateFields();
    if (!data.receive_site) {
      return null;
    }
    if (data.receive_site && data.receive_site[0] == 0) {
      let arr = [];
      this.state.siteTreeData[0] &&
        this.state.siteTreeData[0].children.forEach(item => {
          arr.push(item.value);
        });
      data.receive_site = arr;
    }
    if (data.about_artical) {
      data.about_artical.map((item, index) => {
        return (data[item] = 1);
      });
    }
    if (data.about_artical.indexOf("is_comment") < 0) {
      data.is_comment = 0;
    }
    if (data.about_artical.indexOf("is_reprint") < 0) {
      data.is_reprint = 0;
    }
    if (data.about_artical.indexOf("is_ad") < 0) {
      data.is_ad = 0;
    }
    if (data.about_artical.indexOf("is_check_comment") < 0) {
      data.is_check_comment = 0;
    }

    if (this.state.showCover === 2) {
      let arr = data.information_img.split(",");
      if (arr.length < 3) {
        message.error("3图模式，封面图不能少于3张.");
        return false;
      }
    }

    if (this.state.showCover === 3) {
      //是否是无图上传
      return data;
    } else {
      if (data.information_img) {
        return data;
      }
    }
  };
  /**
   * 重置表单
   */
  resetFields = () => {
    this.props.form.resetFields();
    this.setState({
      editDatas: []
    });
  };
  /**
   * 设置表单值
   */
  setFields = data => {
    let siteArr = [];
    if (data.push_site) {
      data.push_site.forEach(item => {
        siteArr.push(item.site_id);
      });
    }
    let setData = {};
    setData.information_img = data.img;
    setData.eidtor = data.eidtor;
    setData.is_ad = data.is_ad;
    setData.is_check_comment = data.is_check_comment;
    setData.is_comment = data.is_comment;
    setData.is_crond = data.is_crond;
    setData.is_original = data.is_original;
    setData.is_reprint = data.is_reprint;
    setData.original_intro = data.original_intro;
    setData.original_url = data.original_url;
    setData.reporter = data.reporter;
    setData.resource = data.resource;
    setData.default_thumbs_up_num = data.default_like_count;
    setData.default_scan_num = data.default_scan_count;
    setData.default_forward_num = data.default_share_count;
    setData.about_artical = data.about_artical;
    setData.receive_site = siteArr;
    setData.forward_coefficient = data.forward_coefficient;
    setData.scan_coefficient = data.scan_coefficient;
    setData.thumbs_up_coefficient = data.thumbs_up_coefficient;
    // setData.forward_coefficient = data.forward_coefficient;
    // setData.scan_coefficient = data.scan_coefficient;
    // setData.thumbs_up_coefficient = data.thumbs_up_coefficient;
    //已发布视频不覆盖数据
    if (data.type) {
      let formData = this.props.form.getFieldsValue();
      if (formData.information_img && formData.information_img !== noImg) {
        setData.information_img = formData.information_img;
      } else {
        let img = setData.information_img;
        if (img) {
          let imgUrl = img.split(",");
          if (imgUrl.length > 1) {
            this.setState({
              showCover: 2,
              editDatas: imgUrl
            });
          } else {
            this.setState({
              showCover: 1,
              editDatas: imgUrl
            });
          }
        } else {
          this.setState({
            showCover: 3
          });
        }
        // this.props.form.setFieldsValue(setData);
      }
      // return;
    }

    // let img = setData.information_img;
    // if (img) {
    //   let imgUrl = img.split(",");
    //   if (imgUrl.length > 1) {
    //     this.setState({
    //       showCover: 2,
    //       editDatas: imgUrl
    //     });
    //   } else {
    //     this.setState({
    //       showCover: 1,
    //       editDatas: imgUrl
    //     });
    //   }
    // } else {
    //   this.setState({
    //     showCover: 3
    //   });
    // }
    if (setData.original_url) {
      this.setState({
        radioValue: 2
      });
    }
    setData["about_artical"] = [];
    if (setData.is_comment === 1) {
      setData.about_artical.push("is_comment");
    }
    if (setData.is_reprint === 1) {
      setData.about_artical.push("is_reprint");
    }
    if (setData.is_ad === 1) {
      setData.about_artical.push("is_ad");
    }
    if (setData.is_check_comment === 1) {
      setData.about_artical.push("is_check_comment");
    }
    this.props.form.setFieldsValue(setData);
  };
  /**
   * 封面上传控制
   */
  showCover = e => {
    let show = e.target.value;
    this.setState({
      showCover: show,
      editDatas: []
    });

    this.props.form.setFieldsValue({
      information_img: ""
    });
  };
  /**
   * inputNumber 受控
   */
  scanNum = value => {
    this.setState({
      scanNum: value
    });
  };
  forwardNum = value => {
    this.setState({
      forwardNum: value
    });
  };
  thumbsNum = value => {
    this.setState({
      thumbsNum: value
    });
  };
  render() {
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
      }
    };
    let { thumbsNumPro, forwardNumPro, scanNumPro } = this.state;
    if (!thumbsNumPro) thumbsNumPro = 0;
    if (!forwardNumPro) forwardNumPro = 0;
    if (!scanNumPro) scanNumPro = 0;
    const tProps = {
      treeData: this.state.siteTreeData,
      treeCheckable: true,
      showCheckedStrategy: SHOW_PARENT,
      maxTagCount: 2,
      searchPlaceholder: "请选择推送站点！"
    };
    return (
      <div className="righttwo">
        <h3>基本信息</h3>
        <h3>
          <span style={this.state.showCover === 3 ? { display: "none" } : { color: "red" }}>* </span>封面
        </h3>
        <RadioGroup onChange={this.showCover} value={this.state.showCover} style={{ marginBottom: "12px" }}>
          <Radio value={1}>一图封面</Radio>
          <Radio value={2}>三图封面</Radio>
          <Radio value={3}>无图</Radio>
        </RadioGroup>
        {this.state.showCover === 3 ? "" : <UploadDu one={this.state.showCover} form={this.props.form} isEdit={this.state.editDatas} />}
        <Form>
          <FormItem {...formItemLayout} label="">
            {getFieldDecorator("information_img", {
              rules: [
                {
                  required: this.state.showCover === 3 ? false : true,
                  message: "请上传封面图片"
                }
              ]
            })(<Input style={{ display: "none" }} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="编辑">
            {getFieldDecorator("editor")(<Input className="mon_font" placeholder="请输入编辑" size="small" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="记者">
            {getFieldDecorator("reporter")(<Input className="mon_font" placeholder="请输入记者名称" size="small" />)}
          </FormItem>
          <FormItem {...formItemLayout} label="来源">
            {getFieldDecorator("resource")(<Input className="mon_font" placeholder="请输入来源" size="small" />)}
          </FormItem>
          <Divider />
          <FormItem labelAlign="left" label="选择推送站点">
            {getFieldDecorator("receive_site", {
              rules: [
                {
                  required: true,
                  message: "请选择推送站点"
                }
              ]
            })(<TreeSelect {...tProps} />)}
          </FormItem>
          <Divider />
          <h3>配置</h3>
          <FormItem>
            {getFieldDecorator("about_artical", { initialValue: ["is_comment", "is_reprint", "is_ad"] })(
              <Checkbox.Group style={{ width: "100%" }}>
                <Row>
                  <Col span={24}>
                    <Checkbox value="is_comment">允许评论</Checkbox>
                  </Col>
                  {/* <Col span={24}><Checkbox value="is_ad">允许广告</Checkbox></Col> */}
                  <Col span={24}>
                    <Checkbox value="is_check_comment">
                      评论审核（<span style={{ color: "#999" }}>评论进行人工手动审核</span>）
                    </Checkbox>
                  </Col>
                  <Col span={24}>
                    <Checkbox value="is_reprint">允许转载（分享）</Checkbox>
                  </Col>
                </Row>
              </Checkbox.Group>
            )}
          </FormItem>
          <Divider />
          <FormItem {...formItemLayout} label="是否原创">
            {getFieldDecorator("is_original", { initialValue: 1 })(
              <RadioGroup onChange={this.onChangeRadio}>
                <Radio value={1}>是</Radio>
                <Radio value={2}>否</Radio>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="原创声明" style={this.state.radioValue === 2 ? { display: "none" } : {}}>
            {getFieldDecorator("original_intro")(<TextArea placeholder="原创声明" autosize={{ minRows: 4, maxRows: 6 }} />)}
          </FormItem>
          <FormItem {...formItemLayout} label="原文链接" style={this.state.radioValue === 1 ? { display: "none" } : {}}>
            {getFieldDecorator("original_url")(<TextArea placeholder="原文链接" autosize={{ minRows: 4, maxRows: 6 }} />)}
          </FormItem>
          <Divider />
          <FormItem
            label={
              <span className="title">
                点击量<span className="hs">（点击量 = 基数 + 系数*实际数）</span>
              </span>
            }
          >
            <span>
              {getFieldDecorator("default_scan_num", { initialValue: 0 })(<InputNumber placeholder="基数" min={0} style={{ width: "65px" }} onChange={this.scanNum} />)}+{" "}
              {getFieldDecorator("scan_coefficient", { initialValue: 1 })(<InputNumber placeholder="系数" min={0} style={{ width: "65px" }} onChange={this.scanNum} />)} * {scanNumPro}（实际数） ={" "}
              {scanNumPro * parseInt(this.props.form.getFieldValue("scan_coefficient")) + parseInt(this.props.form.getFieldValue("default_scan_num"))}
            </span>
          </FormItem>
          <FormItem
            label={
              <span className="title">
                转发量<span className="hs">（转发量 = 基数 + 系数*实际数）</span>
              </span>
            }
          >
            <span>
              {getFieldDecorator("default_forward_num", { initialValue: 0 })(<InputNumber placeholder="基数" min={0} style={{ width: "65px" }} onChange={this.forwardNum} />)}+{" "}
              {getFieldDecorator("forward_coefficient", { initialValue: 1 })(<InputNumber placeholder="系数" min={0} style={{ width: "65px" }} onChange={this.scanNum} />)} * {forwardNumPro}（实际数）
              = {forwardNumPro * parseInt(this.props.form.getFieldValue("forward_coefficient")) + parseInt(this.props.form.getFieldValue("default_forward_num"))}
            </span>
          </FormItem>
          <FormItem
            label={
              <span className="title">
                点赞量<span className="hs">（点赞量 = 基数 + 系数*实际数）</span>
              </span>
            }
          >
            <div>
              {getFieldDecorator("default_thumbs_up_num", { initialValue: 0 })(<InputNumber placeholder="基数" min={0} style={{ width: "65px" }} onChange={this.thumbsNum} />)}+{" "}
              {getFieldDecorator("thumbs_up_coefficient", { initialValue: 1 })(<InputNumber placeholder="基数" min={0} style={{ width: "65px" }} onChange={this.thumbsNum} />)} * {thumbsNumPro}
              （实际数） = {thumbsNumPro * parseInt(this.props.form.getFieldValue("thumbs_up_coefficient")) + parseInt(this.props.form.getFieldValue("default_thumbs_up_num"))}
            </div>
          </FormItem>
        </Form>
      </div>
    );
  }
}

const RightTwos = Form.create()(RightTwo);
export default RightTwos;
